package com.lhs.time;


import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@RequiredArgsConstructor
public class HotScoreDecayTask {

    private final StringRedisTemplate redisTemplate;
    private static final String HOT_KEY = "search:hot";

       /**
     * 定时衰减热门排行榜分数
     *
     * 该方法通过定时任务每天凌晨3点执行，对Redis中存储的热门数据进行分数衰减处理。
     * 所有热门项目的分数都会乘以0.9系数，实现热度随时间递减的效果。
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void decayHotScores() {
        // 获取所有热门项目的key集合
        Set<String> keys = redisTemplate.opsForZSet().range(HOT_KEY, 0, -1);
        if (keys != null) {
            // 遍历所有热门项目，将分数衰减10%
            for (String k : keys) {
                Double score = redisTemplate.opsForZSet().score(HOT_KEY, k);
                if (score != null) redisTemplate.opsForZSet().add(HOT_KEY, k, score * 0.9);
            }
        }
    }

}
